package com.qd.panda.service.space;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.math.Money;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.DateUtil;
import com.cdqidi.util.JacksonUtil;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.carpark.CarParkInfoDTO;
import com.qd.common.panda.domain.entity.space.*;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.mapper.space.ParkSpaceMapper;
import com.qd.panda.model.*;
import com.qd.panda.service.info.ParkInfoService;
import com.qd.panda.service.park.CarParkRevenueService;
import com.qd.panda.service.park.CarParkService;
import com.qd.panda.service.plate.UserPlateRelationService;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.util.FileConfirmUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 车位租赁信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ParkSpaceService extends BaseService<ParkSpaceMapper, ParkSpace> {

    private static final String PREFIX_ID = "panda_park_space_sid_{0}";

    private final RedisTemplateUtil<ParkSpace> redisTemplateUtil;
    private final CarParkService carParkService;
    private final CarParkRevenueService carParkRevenueService;
    private final ParkInfoService parkInfoService;
    private final ParkSpaceDateService parkSpaceDateService;
    private final ParkSpaceTenantService parkSpaceTenantService;
    private final UserPlateRelationService userPlateRelationService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ParkSpaceDTO save(ParkSpaceDTO dto) {
        validator(dto);
        final ParkSpace model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ParkSpaceDTO update(ParkSpaceDTO dto) {
        final ParkSpace historyModel = Optional.ofNullable(getById(dto.getSid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final ParkSpace model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<ParkSpace> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<ParkSpace> mList) {
        final List<String> ids = mList.stream().map(ParkSpace::getSid).collect(toList());
        final List<ParkSpace> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param sid 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String sid) {
        final ParkSpace historyModel = Optional.ofNullable(getById(sid)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(sid)) {
                throw new ApiException("删除失败");
            }
            parkSpaceDateService.removeBySid(sid);
            parkSpaceTenantService.removeBySid(sid);
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        ids.forEach(this::removeById);
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(ParkSpaceDTO dto) {
        final QueryWrapper<ParkSpace> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param sid 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String sid) {
        boolean exists = false;
        if (StringUtils.hasLength(sid)) {
            final ParkSpace model = getById(sid);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param sid 主键
     * @return 单条记录
     */
    public ParkSpace getById(String sid) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, sid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(sid), ParkSpace.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param sid 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ParkSpaceDTO getByIdDto(String sid) {
        return Optional.ofNullable(getById(sid)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    public ParkSpace getOne(ParkSpaceDTO dto) {
        final QueryWrapper<ParkSpace> queryWrapper = createQueryWrapper(dto);
        ParkSpace model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ParkSpaceDTO getOneDto(ParkSpaceDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    public List<ParkSpace> getList(ParkSpaceDTO dto) {
        final QueryWrapper<ParkSpace> queryWrapper = createQueryWrapper(dto);
        final List<ParkSpace> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<ParkSpaceDTO> getListDto(ParkSpaceDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<ParkSpaceDTO> page(Page<ParkSpace> page, ParkSpaceDTO dto) {
        final QueryWrapper<ParkSpace> queryWrapper = createQueryWrapper(dto, "t1.");
        queryWrapper.orderByDesc("t1.end_date");
        queryWrapper.orderByDesc("t1.end");
        final IPage<ParkSpaceDTO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<OwnerParkSpaceDTO> ownerPage(IPage<OwnerParkSpaceDTO> page) {
        LocalDate now = LocalDate.now();
        final QueryWrapper<OwnerParkSpaceDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t1.publisher", SecurityUtils.getLoginUser().getUserId());
        queryWrapper.orderByDesc("t1.end_date");
        final IPage<OwnerParkSpaceDTO> iPage = baseMapper.ownerPage(page, queryWrapper, now, now);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<CarOwnerParkSpaceDTO> carOwnerPage(IPage<CarOwnerParkSpaceDTO> page, CarOwnerParkSpaceDTO dto) {
        final QueryWrapper<CarOwnerParkSpaceDTO> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(dto.getEnd())) {
            queryWrapper.eq("t1.end", dto.getEnd());
        }
        if (StringUtils.hasLength(dto.getParkId())) {
            queryWrapper.eq("t1.park_id", dto.getParkId());
        }
        queryWrapper.orderByDesc("t1.end_date", "t1.rentable");
        final IPage<CarOwnerParkSpaceDTO> iPage = baseMapper.carOwnerPage(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 发布人收益列表
     *
     * @param page 分页对象
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<OwnerMyIncomeSpaceDTO> ownMyIncome(IPage<OwnerMyIncomeSpaceDTO> page) {
        final IPage<OwnerMyIncomeSpaceDTO> iPage = baseMapper.ownMyIncome(page, SecurityUtils.getLoginUser().getUserId());
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        return iPage;
    }

    private void buildDisplay(OwnerMyIncomeSpaceDTO ownerMyIncomeSpaceDTO) {
        ownerMyIncomeSpaceDTO.setDeductionTotalRevenueDisplay(ownerMyIncomeSpaceDTO.getDeductionTotalRevenue().stripTrailingZeros().toPlainString());
    }

    private void buildDisplay(CarOwnerParkSpaceDTO carOwnerParkSpaceDTO) {
        carOwnerParkSpaceDTO.setRentableDisplay(MbUtil.idToDisplay(carOwnerParkSpaceDTO.getRentable()));
        carOwnerParkSpaceDTO.setEndDisplay(MbUtil.idToDisplay(carOwnerParkSpaceDTO.getEnd()));
        carOwnerParkSpaceDTO.setLeaseTypeDisplay(MbUtil.idToDisplay(carOwnerParkSpaceDTO.getLeaseType()));
        carOwnerParkSpaceDTO.setDateList(parkSpaceDateService.getListBySidDTO(carOwnerParkSpaceDTO.getSid()));
        if (StringUtils.hasLength(carOwnerParkSpaceDTO.getPlanPic())) {
            if (!carOwnerParkSpaceDTO.getPlanPic().startsWith(ConstantDto.HTTP) && !carOwnerParkSpaceDTO.getPlanPic().startsWith(ConstantDto.HTTPS)) {
                carOwnerParkSpaceDTO.setPlanPic(FileConfirmUtil.getImageFile(carOwnerParkSpaceDTO.getPlanPic()));
            }
        }
        Optional.ofNullable(parkInfoService.getByIdDto(carOwnerParkSpaceDTO.getAid())).ifPresent(parkInfoDTO -> {
            carOwnerParkSpaceDTO.setPlanPic(parkInfoDTO.getPlanPic());
            carOwnerParkSpaceDTO.setPicList(parkInfoDTO.getPicList());
            carOwnerParkSpaceDTO.setPropertyRightList(parkInfoDTO.getPropertyRightList());
        });
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(ParkSpace model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getSid()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<ParkSpace> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getSid())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public ParkSpaceDTO modelToDto(ParkSpace model) {
        if (null == model) {
            return null;
        }
        final ParkSpaceDTO dto = new ParkSpaceDTO();
        dto.setSid(model.getSid());
        dto.setStartDate(DateUtil.localDateToStr(model.getStartDate()));
        dto.setEndDate(DateUtil.localDateToStr(model.getEndDate()));
        Optional.ofNullable(model.getStartHour()).ifPresent(startHour -> dto.setStartHour(DateUtil.localTimeToString(startHour)));
        Optional.ofNullable(model.getEndHour()).ifPresent(endHour -> dto.setEndHour(DateUtil.localTimeToString(endHour)));
        dto.setDays(model.getDays());
        dto.setPublishTime(model.getPublishTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setState(model.getState());
        dto.setExpectedDayRevenue(model.getExpectedDayRevenue());
        dto.setExpectedTotalRevenue(model.getExpectedTotalRevenue());
        dto.setTotalRevenue(model.getTotalRevenue());
        dto.setDeductionTotalRevenue(model.getDeductionTotalRevenue());
        dto.setShareRatio(model.getShareRatio());
        dto.setRefundAmount(model.getRefundAmount());
        dto.setDeductionAmount(model.getDeductionAmount());
        dto.setAid(model.getAid());
        dto.setIsPublish(model.getIsPublish());
        dto.setPublisher(model.getPublisher());
        dto.setParkId(model.getParkId());
        dto.setRentable(model.getRentable());
        dto.setDivideAccounts(model.getDivideAccounts());
        dto.setEnd(model.getEnd());
        dto.setLeaseType(model.getLeaseType());
        dto.setPublishId(model.getPublishId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public ParkSpace dtoToModel(ParkSpaceDTO dto) {
        if (null == dto) {
            return null;
        }
        final ParkSpace model = new ParkSpace();
        model.setSid(dto.getSid());
        model.setStartDate(DateUtil.strToLocalDate(dto.getStartDate()));
        model.setEndDate(DateUtil.strToLocalDate(dto.getEndDate()));
        Optional.ofNullable(dto.getStartHour()).ifPresent(startHour -> model.setStartHour(DateUtil.strToLocalTime(startHour)));
        Optional.ofNullable(dto.getEndHour()).ifPresent(endHour -> model.setEndHour(DateUtil.strToLocalTime(endHour)));
        model.setDays(dto.getDays());
        model.setPublishTime(dto.getPublishTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setState(dto.getState());
        model.setExpectedDayRevenue(dto.getExpectedDayRevenue());
        model.setExpectedTotalRevenue(dto.getExpectedTotalRevenue());
        model.setTotalRevenue(dto.getTotalRevenue());
        model.setDeductionTotalRevenue(dto.getDeductionTotalRevenue());
        model.setShareRatio(dto.getShareRatio());
        model.setRefundAmount(dto.getRefundAmount());
        model.setDeductionAmount(dto.getDeductionAmount());
        model.setAid(dto.getAid());
        model.setIsPublish(dto.getIsPublish());
        model.setPublisher(dto.getPublisher());
        model.setParkId(dto.getParkId());
        model.setRentable(dto.getRentable());
        model.setDivideAccounts(dto.getDivideAccounts());
        model.setEnd(dto.getEnd());
        model.setLeaseType(dto.getLeaseType());
        model.setPublishId(dto.getPublishId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(ParkSpaceDTO dto) {
        dto.setStateDisplay(StateUtilService.idToDisplay(dto.getState()));
        dto.setRentableDisplay(MbUtil.idToDisplay(dto.getRentable()));
        dto.setIsPublishDisplay(MbUtil.idToDisplay(dto.getIsPublish()));
        dto.setDeductionAmountDisplay(dto.getDeductionAmount().stripTrailingZeros().toPlainString());
        dto.setDeductionTotalRevenueDisplay(dto.getDeductionTotalRevenue().stripTrailingZeros().toPlainString());
        dto.setRefundAmountDisplay(dto.getRefundAmount().stripTrailingZeros().toPlainString());
        dto.setTotalRevenueDisplay(dto.getTotalRevenue().stripTrailingZeros().toPlainString());
        dto.setExpectedDayRevenueDisplay(dto.getExpectedDayRevenue().stripTrailingZeros().toPlainString());
        dto.setExpectedTotalRevenueDisplay(dto.getExpectedTotalRevenue().stripTrailingZeros().toPlainString());
        dto.setParkIdDisplay(carParkService.idToDisplay(dto.getParkId()));
        dto.setDivideAccountsDisplay(MbUtil.idToDisplay(dto.getDivideAccounts()));
        dto.setEndDisplay(MbUtil.idToDisplay(dto.getEnd()));
        Optional.ofNullable(parkInfoService.getByIdDto(dto.getAid())).ifPresent(dto::setParkInfo);
        dto.setLeaseTypeDisplay(MbUtil.idToDisplay(dto.getLeaseType()));
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(OwnerParkSpaceDTO dto) {
        dto.setStateDisplay(StateUtilService.idToDisplay(dto.getState()));
        dto.setIsPublishDisplay(MbUtil.idToDisplay(dto.getIsPublish()));
        dto.setEndDisplay(MbUtil.idToDisplay(dto.getEnd()));
        dto.setLeaseTypeDisplay(MbUtil.idToDisplay(dto.getLeaseType()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<ParkSpaceDTO> modelToDtoList(List<ParkSpace> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<ParkSpace> dtoToModelList(List<ParkSpaceDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<ParkSpace> createQueryWrapper(ParkSpaceDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<ParkSpace> createQueryWrapper(ParkSpaceDTO dto, String tableAlias) {
        final QueryWrapper<ParkSpace> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getAid())) {
                queryWrapper.eq(tableAlias + "aid", dto.getAid());
            }
            if (StringUtils.hasLength(dto.getIsPublish())) {
                queryWrapper.eq(tableAlias + "is_publish", dto.getIsPublish());
            }
            if (StringUtils.hasLength(dto.getPublisher())) {
                queryWrapper.eq(tableAlias + "publisher", dto.getPublisher());
            }
            if (StringUtils.hasLength(dto.getParkId())) {
                queryWrapper.eq(tableAlias + "park_id", dto.getParkId());
            }
            if (StringUtils.hasLength(dto.getRentable())) {
                queryWrapper.eq(tableAlias + "rentable", dto.getRentable());
            }
            if (StringUtils.hasLength(dto.getEnd())) {
                queryWrapper.eq(tableAlias + "end", dto.getEnd());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<ParkSpace> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<ParkSpace> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(ParkSpace::getSid).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    private void validator(ParkSpaceDTO dto) {
        ParkInfo parkInfo = Optional.ofNullable(parkInfoService.getById(dto.getAid())).orElseThrow(() -> new ApiException("车位ID不存在"));
        CarPark carPark = Optional.ofNullable(carParkService.getById(parkInfo.getParkId())).orElseThrow(() -> new ApiException("停车场ID不存在"));
        buildCarParkRevenue(dto, carPark);
        dto.setShareRatio(carPark.getShareRatio());
        dto.setParkId(parkInfo.getParkId());
        if (!StringUtils.hasLength(dto.getRentable())) {
            dto.setRentable(ConstantDto.SF1);
        }
        if (!StringUtils.hasLength(dto.getDivideAccounts())) {
            dto.setDivideAccounts(ConstantDto.SF0);
        }
        if (!StringUtils.hasLength(dto.getEnd())) {
            dto.setEnd(ConstantDto.SF0);
        }
        if (null == dto.getTotalRevenue()) {
            dto.setTotalRevenue(new BigDecimal("0"));
        }
        if (null == dto.getDeductionTotalRevenue()) {
            dto.setDeductionTotalRevenue(new BigDecimal("0"));
        }
        if (null == dto.getRefundAmount()) {
            dto.setRefundAmount(new BigDecimal("0"));
        }
        if (null == dto.getDeductionAmount()) {
            dto.setDeductionAmount(new BigDecimal("0"));
        }
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        if (dto.getLeaseType().equals(PandaConstant.LEASE_TYPE_HOUR)) {
            startDate = startDate + " " + dto.getStartHour();
            endDate = endDate + " " + dto.getEndHour();
        }
        String s = getBaseMapper().existsDate(dto.getPublisher(), dto.getAid(), startDate, endDate);
        log.info("判断能否发布,publisher: {},aid: {},startDate: {},endDate: {},sid: {}", dto.getPublisher(), dto.getAid(), startDate, endDate, s);
        if (StringUtils.hasLength(s)) {
            throw new ApiException("当前时段包含了还未结束的租赁,不能发布");
        }
        if (dto.getLeaseType().equals(PandaConstant.LEASE_TYPE_HOUR)) {
            String start = dto.getStartDate() + " 00:00:00";
            s = getBaseMapper().existsDate(dto.getPublisher(), dto.getAid(), start, start);
            log.info("判断能否发布,publisher: {},aid: {},startDate: {},endDate: {},sid: {}", dto.getPublisher(), dto.getAid(), start, start, s);
            if (StringUtils.hasLength(s)) {
                throw new ApiException("当前时段包含了还未结束的租赁,不能发布");
            }
        }
        parkSpaceDateService.saveDateList(dto);
    }


    @Transactional(rollbackFor = Exception.class)
    public void stop(ParkSpaceDTO dto) {
        LocalDate now = LocalDate.now();
        ParkSpaceDTO parkSpace = Optional.ofNullable(getByIdDto(dto.getSid())).orElseThrow(() -> new ApiException("主键值错误"));
        if (parkSpace.getEnd().equals(ConstantDto.SF1)) {
            throw new ApiException("已经结束,不能操作");
        }
        List<ParkSpaceTenant> list = parkSpaceTenantService.getPaySuccess(parkSpace.getSid());
        if (!list.isEmpty()) {
            //有支付成功的,如果有判断是否有大于或者等于当前时间的，如果有，那么不能停止
            boolean b = list.stream().map(t -> DateUtil.getDatesBetween(t.getStartDate(), t.getEndDate())).anyMatch(l -> {
                for (LocalDate localDate : l) {
                    if (localDate.equals(now)) {
                        return true;
                    }
                    if (localDate.isAfter(now)) {
                        return true;
                    }
                }
                return false;
            });
            if (b) {
                throw new ApiException(20001, "已经有支付成功的,不能停止");
            }
        }
        parkSpace.setState(dto.getState());
        parkSpace.setEnd(dto.getEnd());
        parkSpace.setRentable(dto.getRentable());
        update(parkSpace);
        parkSpace.freeData();
    }

    @Transactional(readOnly = true)
    public ObjectNode expectedRevenue(ParkSpaceDTO dto) {
        ParkInfo parkInfo = Optional.ofNullable(parkInfoService.getById(dto.getAid())).orElseThrow(() -> new ApiException("车位ID不存在"));
        CarPark carPark = Optional.ofNullable(carParkService.getById(parkInfo.getParkId())).orElseThrow(() -> new ApiException("停车场ID不存在"));
        buildCarParkRevenue(dto, carPark);
        Money expectedDayRevenue = new Money(dto.getExpectedDayRevenue()).multiply(carPark.getShareRatio()).divide(100D);
        Money expectedTotalRevenue = new Money(dto.getExpectedTotalRevenue()).multiply(carPark.getShareRatio()).divide(100D);
        dto.setExpectedDayRevenueDisplay(expectedDayRevenue.getAmount().stripTrailingZeros().toPlainString());
        ObjectNode objectNode = JacksonUtil.getObjectMapper().createObjectNode();
        objectNode.put("expectedTotalRevenueDisplay", expectedTotalRevenue.getAmount().stripTrailingZeros().toPlainString());
        objectNode.put("expectedDayRevenueDisplay", expectedDayRevenue.getAmount().stripTrailingZeros().toPlainString());
        objectNode.put("days", dto.getDays());
        return objectNode;
    }

    public void buildCarParkRevenue(ParkSpaceDTO dto, CarPark carPark) {
        LocalDate start = DateUtil.strToLocalDate(dto.getStartDate());
        LocalDate end = DateUtil.strToLocalDate(dto.getEndDate());
        if (end.isBefore(start)) {
            throw new ApiException("开始时间和结束时间填写错误");
        }
        if (StringUtils.hasLength(dto.getLeaseType())) {
            if (dto.getLeaseType().equals(PandaConstant.LEASE_TYPE_DAY)) {
                if (StringUtils.hasLength(dto.getStartHour())) {
                    throw new ApiException("开始小时不能有值");
                }
                if (StringUtils.hasLength(dto.getEndHour())) {
                    throw new ApiException("结束小时不能有值");
                }
                long days = (end.toEpochDay() - start.toEpochDay()) + 1;
                if (days < 2) {
                    throw new ApiException("两天起租");
                }
                if (days > 30) {
                    throw new ApiException("租赁时间最长不能超过30天");
                }
                dto.setDays(days);
            } else if (dto.getLeaseType().equals(PandaConstant.LEASE_TYPE_HOUR)) {
                if (!dto.getStartDate().equals(dto.getEndDate())) {
                    throw new ApiException("开始时间和结束时间必须一致");
                }
                if (!StringUtils.hasLength(dto.getStartHour())) {
                    throw new ApiException("开始小时不能为空");
                }
                if (!StringUtils.hasLength(dto.getEndHour())) {
                    throw new ApiException("结束小时不能为空");
                }
                LocalTime startHour = DateUtil.strToLocalTime(dto.getStartHour());
                LocalTime endHour = DateUtil.strToLocalTime(dto.getEndHour());
                if (endHour.isBefore(startHour) || startHour.equals(endHour)) {
                    throw new ApiException("开始小时和结束小时填写错误");
                }
                long minutes = Duration.between(startHour, endHour).toMinutes();
                long hours = minutes / 60;
                long hoursRemainder = minutes % 60;
                if (hoursRemainder > 0) {
                    hours += 1;
                }
                if (hours < 2) {
                    throw new ApiException("两小时起租");
                }
                dto.setDays(hours);
            } else {
                throw new ApiException("租赁类型值错误");
            }
        }

        if (null == carPark.getShareRatio() || carPark.getShareRatio() < 10) {
            throw new ApiException("请设置停车场的ShareRatio");
        }
        List<CarParkRevenue> carParkRevenueList = carParkRevenueService.getListByPid(carPark.getPId());
        if (carParkRevenueList.isEmpty()) {
            throw new ApiException("请设置停车场收益");
        }
        if (StringUtils.hasLength(dto.getLeaseType())) {
            Optional<CarParkRevenue> optional;
            if (dto.getLeaseType().equals(PandaConstant.LEASE_TYPE_DAY)) {
                optional = carParkRevenueList.stream().filter(p -> p.getLeaseType().equals(dto.getLeaseType())).filter(p -> p.getDays() >= dto.getDays()).max(Comparator.comparingInt(o -> o.getDayRevenue().multiply(BigDecimal.valueOf(dto.getDays())).intValue()));
            } else {
                optional = carParkRevenueList.stream().filter(p -> p.getLeaseType().equals(dto.getLeaseType())).max(Comparator.comparingInt(o -> o.getDayRevenue().multiply(BigDecimal.valueOf(dto.getDays())).intValue()));
            }
            if (optional.isEmpty()) {
                throw new ApiException("没有符合要求的收益");
            }
            CarParkRevenue carParkRevenue = optional.get();
            dto.setExpectedDayRevenue(carParkRevenue.getDayRevenue());
            dto.setExpectedTotalRevenue(new Money(carParkRevenue.getDayRevenue()).multiply(dto.getDays()).getAmount());
        }
    }

    public void checkDays(ParkSpaceTenantDTO dto) {
        ParkSpace parkSpace = Optional.ofNullable(getById(dto.getSid())).orElseThrow(() -> new ApiException("租赁ID值错误"));
        LocalDate start = DateUtil.strToLocalDate(dto.getStartDate());
        LocalDate end = DateUtil.strToLocalDate(dto.getEndDate());
        if (end.isBefore(start)) {
            throw new ApiException("开始时间和结束时间填写错误");
        }
        if (parkSpace.getLeaseType().equals(PandaConstant.LEASE_TYPE_DAY)) {
            long days = (end.toEpochDay() - start.toEpochDay()) + 1;
            if (days < 2) {
                throw new ApiException("两天起租");
            }
            if (days > 30) {
                throw new ApiException("租赁时间最长不能超过30天");
            }
            if (parkSpace.getStartDate().isAfter(start)) {
                throw new ApiException("租赁开始时间错误");
            }
            if (parkSpace.getEndDate().isBefore(end)) {
                throw new ApiException("租赁结束时间错误");
            }
            LocalDateTime startDate = DateUtil.strToLocalDateTime(dto.getStartDate() + " 00:00:00");
            LocalDateTime endDate = DateUtil.strToLocalDateTime(dto.getEndDate() + " 00:00:00");
            List<LocalDateTime> localDateTimeList = DateUtil.getDatesBetween(startDate, endDate);
            dto.setDateList(localDateTimeList);
            dto.setDays(days);
            dto.setActualDays(days);
        } else if (parkSpace.getLeaseType().equals(PandaConstant.LEASE_TYPE_HOUR)) {
            if (!dto.getStartDate().equals(dto.getEndDate())) {
                throw new ApiException("开始时间和结束时间必须一致");
            }
            if (!StringUtils.hasLength(dto.getStartHour())) {
                throw new ApiException("开始小时不能为空");
            }
            if (!StringUtils.hasLength(dto.getEndHour())) {
                throw new ApiException("结束小时不能为空");
            }
            LocalTime startHour = DateUtil.strToLocalTime(dto.getStartHour());
            LocalTime endHour = DateUtil.strToLocalTime(dto.getEndHour());
            if (endHour.isBefore(startHour) || startHour.equals(endHour)) {
                throw new ApiException("开始小时和结束小时填写错误");
            }
            long minutes = Duration.between(startHour, endHour).toMinutes();
            long hours = minutes / 60;
            long hoursRemainder = minutes % 60;
            if (hoursRemainder > 0) {
                hours += 1;
            }
            if (hours < 2) {
                throw new ApiException("两小时起租");
            }
            //前一个小时如果有人租了，那么当前小时不能选择，因为要给上一个车主留出一个小时的时间
            //比如当前车主选择的开始小时是8,那么需要7点不能租才行
            LocalTime lastHour = startHour.minusHours(1);
            boolean b = parkSpaceDateService.existsByTenantAndLeaseTime(DateUtil.strToLocalDateTime(dto.getStartDate()+" "+DateUtil.localTimeToString(lastHour)), dto.getSid());
            if(b){
                throw new ApiException("开始时间不能选择");
            }
            dto.setDays(hours);
            dto.setActualDays(hours);
            LocalDateTime startDate = DateUtil.strToLocalDateTime(dto.getStartDate() + " " + dto.getStartHour());
            LocalDateTime endDate = DateUtil.strToLocalDateTime(dto.getStartDate() + " " + dto.getEndHour());
            List<LocalDateTime> localDateTimeList = DateUtil.getTimesBetween(startDate, endDate);
            dto.setDateList(localDateTimeList);
        } else {
            throw new ApiException("租赁类型值错误");
        }
        String sid = getBaseMapper().paySuccess(dto.getTenant(), dto.getTenantNumber(), dto.getDateList());
        if (StringUtils.hasLength(sid)) {
            log.error("当前车牌号在当前日期已有其他租赁,sid： {}", sid);
            throw new ApiException("当前车牌号在当前日期已有其他租赁");
        }
        List<ParkSpaceDate> list = parkSpaceDateService.getListBySid(dto.getSid());
        if (list.isEmpty()) {
            return;
        }
        List<LocalDateTime> dateList = list.stream().filter(p -> StringUtils.hasLength(p.getTenant())).map(ParkSpaceDate::getLeaseTime).collect(toList());
        log.info("dateList: {}", dateList.size());
        if (!dateList.isEmpty()) {
            //查询出有人付款的日期
            boolean b = CollUtil.containsAny(dto.getDateList(), dateList);
            if (b) {
                throw new ApiException("对不起，您慢了0.1秒，当前时段已被其他用户抢先租赁，请重新选择");
            }
        }

    }

    /**
     * 查询没有结束的车位数量
     *
     * @param carParkInfoDTO 停车场ID
     * @return 数量
     */
    @Transactional(readOnly = true)
    public void numberOfRentable(CarParkInfoDTO carParkInfoDTO) {
        QueryWrapper<ParkSpace> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("lease_type,count(*) as leaveTypeCount");
        queryWrapper.eq("park_id", carParkInfoDTO.getPId());
        queryWrapper.eq("end", ConstantDto.SF0);
        queryWrapper.groupBy("lease_type");
        long leaseTypeHourCount = 0;
        long leaseTypeDayCount = 0;
        List<Map<String, Object>> maps = baseMapper.selectMaps(queryWrapper);
        if(!maps.isEmpty()){
            for(Map<String,Object> m:maps){
                Object o = m.get("lease_type");
                if (PandaConstant.LEASE_TYPE_HOUR.equals(o)) {
                    leaseTypeHourCount = Long.parseLong(m.get("leaveTypeCount").toString());
                } else if (PandaConstant.LEASE_TYPE_DAY.equals(o)) {
                    leaseTypeDayCount = Long.parseLong(m.get("leaveTypeCount").toString());
                }
            }
        }
        carParkInfoDTO.setRentableDayParkSpacesNum(leaseTypeDayCount);
        carParkInfoDTO.setRentableHourParkSpacesNum(leaseTypeHourCount);
        queryWrapper.clear();
    }

    @Transactional(readOnly = true)
    public CarOwnerParkSpaceDTO getByCarOwnerParkSpace(String id) {
        CarOwnerParkSpaceDTO carOwnerParkSpaceDTO = getBaseMapper().getCarOwnerById(id);
        Optional.ofNullable(carOwnerParkSpaceDTO).ifPresent(c -> {
            buildDisplay(c);
            List<UserPlateRelation> list = userPlateRelationService.getUserPlateRelationByUserId(SecurityUtils.getLoginUser().getUserId());
            if (!list.isEmpty()) {
                List<String> ids = list.stream().map(UserPlateRelation::getPlateNumber).collect(toList());
                carOwnerParkSpaceDTO.setParkNumberList(ids);
            }
        });
        return carOwnerParkSpaceDTO;
    }

    @Transactional(readOnly = true)
    public ObjectNode calculatePrice(ParkSpaceTenantDTO dto) {
        ParkSpaceDTO parkSpace = Optional.ofNullable(getByIdDto(dto.getSid())).orElseThrow(() -> new ApiException("租赁ID值不存在"));
        if (parkSpace.getEnd().equals(ConstantDto.SF1)) {
            throw new ApiException("当前租赁已经结束");
        }
        checkDays(dto);
        List<CarParkRevenue> carParkRevenueList = carParkRevenueService.getListByPid(parkSpace.getParkId());
        if (carParkRevenueList.isEmpty()) {
            throw new ApiException("请设置停车场收益");
        }
        CarParkRevenue carParkRevenue = null;
        if (StringUtils.hasLength(parkSpace.getLeaseType())) {
            Optional<CarParkRevenue> optional;
            if (parkSpace.getLeaseType().equals(PandaConstant.LEASE_TYPE_DAY)) {
                optional = carParkRevenueList.stream().filter(p -> p.getLeaseType().equals(parkSpace.getLeaseType())).filter(p -> p.getDays() >= dto.getDays()).max(Comparator.comparingInt(o -> o.getDayRevenue().multiply(BigDecimal.valueOf(dto.getDays())).intValue()));
            } else {
                optional = carParkRevenueList.stream().filter(p -> p.getLeaseType().equals(parkSpace.getLeaseType())).max(Comparator.comparingInt(o -> o.getDayRevenue().multiply(BigDecimal.valueOf(dto.getDays())).intValue()));
            }
            if (optional.isEmpty()) {
                throw new ApiException("没有符合要求的收益");
            }
            carParkRevenue = optional.get();
        }
        if (null == carParkRevenue) {
            throw new ApiException("没有符合要求的收益");
        }
        ObjectNode objectNode = JacksonUtil.getObjectMapper().createObjectNode();
        objectNode.put("leaseType",parkSpace.getLeaseType());
        objectNode.put("leaseTypeDisplay",parkSpace.getLeaseTypeDisplay());
        objectNode.put("days", dto.getDays());
        objectNode.put("dailyFee", carParkRevenue.getDayRevenue().stripTrailingZeros().toPlainString());
        BigDecimal total = new Money(carParkRevenue.getDayRevenue()).multiply(dto.getDays()).getAmount();
        objectNode.put("totalCost", total.stripTrailingZeros().toPlainString());
        return objectNode;
    }

    @Transactional(readOnly = true)
    public ObjectNode ownParkAmount(String userId) {
        ObjectNode objectNode = JacksonUtil.getObjectMapper().createObjectNode();
        //合计金额
        BigDecimal totalAmount;
        //已到账金额
        BigDecimal receivedAmount;
        //未到账金额
        BigDecimal notReceivedAmount;
        Map<String, Object> map = baseMapper.ownParkAmount(userId);
        if (null == map || map.isEmpty()) {
            totalAmount = new BigDecimal("0");
            receivedAmount = new BigDecimal("0");
        } else {
            notReceivedAmount = getAmount(map.get(ConstantDto.SF0));
            receivedAmount = getAmount(map.get(ConstantDto.SF1));
            totalAmount = new Money(receivedAmount).add(new Money(notReceivedAmount)).getAmount();
        }
        objectNode.put("totalAmount", totalAmount.stripTrailingZeros().toPlainString());
        objectNode.put("receivedAmount", receivedAmount.stripTrailingZeros().toPlainString());
        return objectNode;
    }

    @SuppressWarnings(value = "unchecked")
    private BigDecimal getAmount(Object object) {
        if (null == object) {
            return new BigDecimal("0");
        }
        Map<String, Object> o = (Map<String, Object>) object;
        Object amount = o.get("amount");
        return new BigDecimal(amount.toString());
    }

    @Transactional(readOnly = true)
    public List<ParkSpace> getListByPublishId(String publishId) {
        final QueryWrapper<ParkSpace> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publish_id", publishId);
        List<ParkSpace> parkSpaces = baseMapper.selectList(queryWrapper);
        queryWrapper.clear();
        return parkSpaces;
    }
}